package tw.asap.plus.ui.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Observer;

import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import tw.asap.plus.R;
import tw.asap.plus.common.ConstValue;
import tw.asap.plus.entity.CartBean;
import tw.asap.plus.entity.SubCartBean;
import tw.asap.plus.entity.request.GoodsItemRequest;
import tw.asap.plus.entity.response.GoodsDetailNV;
import tw.asap.plus.entity.response.ResponseDataWrapper;
import tw.asap.plus.entity.response.ShopIndex;
import tw.asap.plus.network.config.HRetrofitCreator;
import tw.asap.plus.network.service.MerchantService;
import tw.asap.plus.presenter.CartPresenter;
import tw.asap.plus.presenter.CartPresenterImpl;
import tw.asap.plus.ui.AsapBaseActivity;
import tw.asap.plus.ui.adapter.PinedSectionAdapter;
import tw.asap.plus.ui.custom.AppBar;
import tw.asap.plus.ui.custom.CartView;
import tw.asap.plus.ui.custom.OnTagClickListener;
import tw.asap.plus.ui.custom.QuantityController;
import tw.asap.plus.ui.custom.Tag;
import tw.asap.plus.ui.custom.TagView;
import tw.asap.plus.ui.fragment.WebviewFragment;
import tw.asap.plus.utils.Toaster;
import tw.asap.plus.utils.Utils;

/**
 * Created by Yax.
 * Date: 15/11/15
 * Time: 下午9:47
 * Description:
 */
public class GoodsDetailActivity extends AsapBaseActivity implements Observer {


    PinedSectionAdapter.GoodsItem goodsInfo;
    ShopIndex.ShopEntity shopInfo;

    CartPresenter cartPresenter = MerchantActivity.getCartPresenter();
    @InjectView(R.id.appbar)
    AppBar appbar;
    @InjectView(R.id.goods_img)
    SimpleDraweeView goodsImg;
    @InjectView(R.id.goods_name)
    TextView goodsName;
    @InjectView(R.id.price)
    TextView price;
    @InjectView(R.id.old_price)
    TextView oldPrice;
    @InjectView(R.id.quantity_controller)
    QuantityController quantityController;
    @InjectView(R.id.fl_webview)
    FrameLayout flWebview;
    @InjectView(R.id.ll_content)
    LinearLayout llContent;
    @InjectView(R.id.cart_view)
    CartView cartView;
    @InjectView(R.id.ll_property)
    LinearLayout llProperty;
    HashMap<String, GoodsDetailNV.PropsEntity.ValuesEntity> propertyMap;
    boolean hasProperty;
    @InjectView(R.id.add_to_cart)
    TextView addToCart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_detail);
        ButterKnife.inject(this);
        appbar.setLeftClickEvent(v -> {
            finish();
        });
        goodsInfo = getIntent().getParcelableExtra("GOODS_INFO");
        shopInfo = getIntent().getParcelableExtra("SHOP_INFO");
        getGoodsDetail(goodsInfo.itemEntity.getId());
    }

    private void fillData(GoodsDetailNV data) {
        hasProperty = data.getProps() != null && data.getProps().size() > 0;
        if (hasProperty) {
            goodsInfo.count = 1;
            addToCart.setVisibility(View.VISIBLE);
            addToCart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (propertyMap.size() < data.getProps().size()) {
                        Toaster.s(GoodsDetailActivity.this, getString(R.string.please_choose_property));
                    } else if (quantityController.getCount() < 1) {
                        Toaster.s(GoodsDetailActivity.this, getString(R.string.please_choose_num));
                    } else {
                        SubCartBean subCartBean = new SubCartBean();
                        subCartBean.setCount(goodsInfo.count);
                        subCartBean.setPropertyMap(propertyMap);
                        subCartBean.setGoodsId(goodsInfo.itemEntity.getId());
                        cartPresenter.addSubItem(subCartBean, goodsInfo);
                        finish();
                    }
                }
            });
            propertyMap = new HashMap<>();
            llProperty.setVisibility(View.VISIBLE);
            LayoutInflater inflater = LayoutInflater.from(this);
            for (int i = 0; i < data.getProps().size(); i++) {
                GoodsDetailNV.PropsEntity entity = data.getProps().get(i);
                LinearLayout linearLayout = (LinearLayout) inflater.inflate(R.layout.view_property, null);
                ((TextView) linearLayout.findViewById(R.id.property_name)).setText(entity.getName());
                TagView tagView = (TagView) linearLayout.findViewById(R.id.tagView);
                tagView.setOnTagClickListener(new OnTagClickListener() {
                    @Override
                    public void onTagClick(Tag tag, int position) {
                        propertyMap.put(entity.getPropkey_id(), ((GoodsDetailNV.PropsEntity.ValuesEntity) tag.getTag()));
                        for (Tag tag1 : tagView.getTags()) {
                            tag1.isChecked = false;
                        }
                        tag.isChecked = true;
                    }
                });
                for (GoodsDetailNV.PropsEntity.ValuesEntity key : entity.getValues()) {
                    Tag tag = new Tag(key.getValue());
                    tag.layoutColor = getResources().getColor(R.color.white);
                    tag.layoutColorPress = getResources().getColor(R.color.asap_green);
                    tag.layoutBorderColor = getResources().getColor(R.color.palette_gray_light);
                    tag.layoutBorderSize = 1l;
                    tag.radius = 10l;
                    tag.setTag(key);
                    tagView.addTag(tag);
                }
                llProperty.addView(linearLayout, llProperty.getChildCount() - 1);
            }
        }


        goodsName.setText(goodsInfo.itemEntity.getTitle());
        if (!TextUtils.isEmpty(data.getBgimg())) {
            goodsImg.setImageURI(Uri.parse(data.getBgimg()));
        } else {
            goodsImg.setImageURI(Uri.parse(goodsInfo.itemEntity.getImg()));
        }

        price.setText("$".concat(Utils.getFormatAmt(data.getPrice())));
        oldPrice.setText("$".concat(Utils.getFormatAmt(data.getPrice_init())));
        oldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中间横线

        String url = "";
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (!TextUtils.isEmpty(data.getUrl())) {
            url = data.getUrl();
            if (!url.startsWith(ConstValue.TEST_URL)) {
                url = ConstValue.TEST_URL.concat(url);
            }
        }

        WebviewFragment fragment = WebviewFragment.newInstance(url, goodsInfo.itemEntity.getId());
        transaction.replace(R.id.fl_webview, fragment);
        transaction.commitAllowingStateLoss();
        cartPresenter.bindView(cartView, () -> {
            if (cartPresenter.getCartGoodsList() != null) {
                ArrayList<CartBean> list = (ArrayList<CartBean>) cartPresenter.getCartGoodsList();
                Intent intent = new Intent(this, OrderConfirmActivity.class);
                intent.putExtra("GOODS_LIST", list);
                intent.putExtras(getIntent());
                startActivity(intent);
            }
        });

        ((CartPresenterImpl) cartPresenter).registerObserver(this);

        quantityController.setStatus(goodsInfo.count);
        quantityController.setOnMinusListener(newQuantity -> {
            if (cartPresenter != null && !hasProperty) {
                cartPresenter.minus(goodsInfo);
            } else {
                if (goodsInfo.count == 0) {
                    return;
                }
                goodsInfo.count--;
                quantityController.setStatus(goodsInfo.count);
            }
        });
        quantityController.setOnAddListener(newQuantity -> {
            if (cartPresenter != null && !hasProperty) {
                cartPresenter.add(goodsInfo);
            } else {
                goodsInfo.count++;
                quantityController.setStatus(goodsInfo.count);
            }
        });
    }


    private void getGoodsDetail(String goodsId) {
        HRetrofitCreator creator = HRetrofitCreator.getInstance();
        Observable.create(new Observable.OnSubscribe<ResponseDataWrapper<GoodsDetailNV>>() {
            @Override
            public void call(Subscriber<? super ResponseDataWrapper<GoodsDetailNV>> subscriber) {
                MerchantService service = creator.getService(MerchantService.class);
                subscriber.onNext(service.getNewGoodsDetail(new GoodsItemRequest(shopInfo.getShopkey(), goodsId)));
                subscriber.onCompleted();
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<ResponseDataWrapper<GoodsDetailNV>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(ResponseDataWrapper<GoodsDetailNV> response) {
                        if (response.respcd.equals(ConstValue.RESPCD)) {
                            fillData(response.data);
                        }
                    }
                });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ((CartPresenterImpl) cartPresenter).unRegisterObserver(this);
    }

    @Override
    public void update(java.util.Observable observable, Object data) {
        if (data instanceof Integer && (Integer) data == -1) {
            quantityController.setStatus(0);
            return;
        }
        if (data != null) {
            quantityController.setStatus(Integer.parseInt(((CartBean) data).item_nums));
        }
    }
}
